﻿using Bit.Art.Api.Conventions;
using Bit.Art.Api.Models;
using Bit.Art.Core.Extensions;
using Bit.Art.Distributed;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

namespace Bit.Art.Api
{
    /// <summary>
    /// 
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// 
        /// </summary>
        public IConfiguration Configuration { get; }

        /// <summary>
        /// 
        /// </summary>
        public IHostingEnvironment Environment { get; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="environment"></param>
        public Startup(IConfiguration configuration, IHostingEnvironment environment)
        {
            Configuration = configuration;
            Utility.Configuration = (IConfigurationRoot)configuration;
            Environment = environment;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            services.AddCors();
            services.AddMvc(options=> 
            {
                options.Conventions.Add(new RouteConvention(new RouteAttribute("api/[controller]/[action]")));
            });

            services.AddSingleton(
                ApplicationLogging.LoggerFactory.AddConsole(Configuration.GetSection("Logging")));
            services.AddLogging();
            services.AddSingleton(Memcache.Create(Configuration["redis"]));
            services.Configure<ServerOptions>(Configuration);

            services.AddMvcCore()
                .AddAuthorization(options =>
                {
                    options.AddPolicy("market", policy => policy.RequireClaim("scope", "market"));
                    options.AddPolicy("account", policy => policy.RequireClaim("scope", "account"));
                    options.AddPolicy("partner", policy => policy.RequireClaim("scope", "partner"));
                    options.AddPolicy("profile", policy => policy.RequireClaim("scope", "profile"));
                })
                .AddJsonFormatters();

            services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = Configuration["SsoOption:ServerUrl"];
                    options.RequireHttpsMetadata = false;
                });

            // Register the Swagger generator, defining one or more Swagger documents
            // 对oauth2的支持，参考：http://dave.vanherten.ca/2017/03/swagger-identityserver4-part2/
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "交易所节点API", Version = "v0.0.1.1" });
                var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);

                c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type = "oauth2",
                    Flow = "implicit",
                    AuthorizationUrl = string.Format($"{Configuration["sso_server"]}/connect/authorize"),
                    TokenUrl = string.Format($"{Configuration["sso_server"]}/connect/token"),
                    Scopes = new Dictionary<string, string>
                    {
                        { "market", "交易相关的API" },
                        { "account", "提现相关的API" },
                        { "openid", "openid" },
                        { "profile", "用户个人信息" }
                    }
                });

                c.OperationFilter<AuthorizeCheckOperationFilter>();
                c.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="loggerFactory"></param>
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                //app.UseExceptionHandler(builder => builder.Run(async context => await HttpApiHelper.HandleException(context)));
                app.UseDeveloperExceptionPage();
            }
            //else
            //    app.UseExceptionHandler(builder => builder.Run(async context => await HttpApiHelper.HandleException(context)));

            loggerFactory.AddConsole().AddDebug();
            app.UseCors(builder =>
                builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
            
            app.UseAuthentication();

            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "交易所节点API V1");
                // c.OAuthClientId(Configuration["swagger_sso_client_id"]);
            });

            app.UseMvc();
            app.UseStaticFiles();
        }
    }
}
